<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	  xmlns:th="http://www.thymeleaf.org"
	  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
	<meta charset="utf-8">
	<title></title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" th:href="@{/js/layui-v2.4.5/layui/css/layui.css}" media="all" />
	<link rel="stylesheet" th:href="@{/css/public.css}" media="all" />
</head>
<body class="childrenBody"  style="-webkit-backface-visibility: hidden;">
<form class="layui-form">
	<blockquote class="layui-elem-quote quoteBox">
		<form class="layui-form">
			<div class="layui-inline">
				<label class="layui-form-label" style="text-align: left;width: 50px">用户名</label>
				<div class="layui-input-inline">
					<input type="text" class="layui-input searchVal" placeholder="用户名"  name = "username"/>
				</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label" style="text-align: left;width: 60px">生效状态</label>
				<div class="layui-input-inline"  style="width: 120px">
					<select name="enabled" id ="enabled">
						<option value="1" >有效</option>
						<option value="0">无效</option>
					</select>
				</div>
			</div>
			<a class="layui-btn search_btn"  lay-submit data-type="reload" lay-filter="query">搜索</a>
			<div class="layui-inline">

				<a class="layui-btn layui-btn-normal addNews_btn" id="addUser">添加用户</a>
			</div>

		</form>
	</blockquote>
	<table id="userList" lay-filter="userList"></table>

	<!--操作-->
	<script type="text/html" id="newsListBar">
		<a class="layui-btn layui-btn-xs layui-btn-normal " lay-event="show">查看菜单权限</a>

		{{#  if(d.enabled){ }}
		<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">失效用户</a>
		{{#  }else{ }}
		<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="valid">生效用户</a>
		{{#  } }}
	</script>
</form>
<style>
	.layui-unselect .layui-form-select{}
</style>
<script th:src="@{/js/jquery-2.1.1.min.js}"></script>
<script th:src="@{/js/layui-v2.4.5/layui/layui.js}"></script>
<script th:src="@{/js/utils.js}"></script>
<script type="text/javascript">
    var hasSave = false;
	layui.use(['table','form'], function(){
	var table = layui.table,form = layui.form;

	var mytable = table.render({
		elem: '#userList'
		,url:path+"/users/listUsers"
		,title: '用户'
        ,where:{"params['enabled']":1}
        ,cols: [ [ //标题栏
            {field: 'username', title:'用户名', width:100}
            ,{field: 'name', title:'昵称', width:100}
            ,{field: 'headImgUrl', title:'头像', width:80}
            ,{field: 'roles', title:'所属角色', width:180 ,templet: function(d){
                var htm = "";
				if(d.roles!=null&&d.roles.length>0){

				    $.each(d.roles,function(i,value){
				        if(i==0){
                            htm +=value.roleName;
						}else{
                            htm += ","+value.roleName;
						}

					})
				}
				return htm;
        	}}
            ,{field: 'privs', title:'用户权限', width:180 ,templet: function(d){
                var htm = "";
                if(d.privs!=null&&d.privs.length>0){

                    $.each(d.privs,function(i,value){
                        if(i==0){
                            htm +=value.privName;
                        }else{
                            htm += ","+value.privName;
                        }
                    })
                }
                return htm;
            }}
            ,{field: 'createTime', title:'创建时间', width:160}
            ,{field: 'modTime', title:'修改时间', width:160}
            ,{ title:'操作', toolbar: '#newsListBar', width:260}
        ]]
		,page: true
        ,even: true
        ,page: {   //自定义分页条
            limit: 10
            ,curr: 1
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip']
			,hash:"offset"
        }
        ,done: function(res, curr, count){

        }
        ,request: {
            pageName: 'offset' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
		});


        /**
         * 监听查询按钮
         *
         */
        form.on('submit(query)', function(data){
            tableReload(data.field);
        });


        var tableReload = function (data) {
            mytable.reload({
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                ,where:{"params['username']":data.username,"params['enabled']":data.enabled}
                , done: function (res, curr, count) {

                }
            })

        }

        //监听操作工具栏
        table.on('tool(userList)', function(obj){

            var rowData = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            var tr = obj.tr; //获得当前行 tr 的DOM对象
            switch (layEvent){
                case 'edit':
                    addOrUpdateUser(true,rowData.id)
                    break;
                case 'del':
                    del(rowData.id);
                    break;
				case 'show':
                    showResource(rowData.id)
                    break;
                default:
                    layer.alert("未知的操作类型",{icon: 5});
            }

        });

        var showResource = function(userId){
            layer.open({
                type: 2,
                title: "所属菜单权限",
                closeBtn: 1, //不显示关闭按钮
//                shade: [0],
                area: ['400px', '400px'],
//                offset: 'rb', //右下角弹出
                anim: 2,
                shadeClose:true,
                content: [path+'/resource/showPriv?userId='+userId], //iframe的url，no代表不显示滚动条
            });
		}


        /**
         * 删除方法
         * */

        var del = function (id) {
            var load = layer.load();
            $.ajax({
                type: "POST",
                url:  path+'/users/deleteUser',
                dataType:"json",
                data:{"id":id,"enabled":"0"},
                success: function (data) {
                    layer.close(load);
                    layer.msg(data.msg,{icon: 6});
                    if(data.code>0){
                        var data = {"username":$("#name").val(),"enabled":$("#enabled").val()}
                        tableReload(data);
                    }

                },
                error: function (msg) {
                    layer.close(load);
                    layer.msg("删除失败",{icon: 5})

                }
            });
        }


        var valid = function (id) {
            var load = layer.load();
            $.ajax({
                type: "POST",
                url:  path+'/users/validUser',
                dataType:"json",
                data:{"id":id,"enabled":"1"},
                success: function (data) {
                    layer.close(load);
                    layer.msg(data.msg,{icon: 6});
                    if(data.code>0){
                        var data = {"username":$("#name").val(),"enabled":$("#enabled").val()}
                        tableReload(data);
                    }

                },
                error: function (msg) {
                    layer.close(load);
                    layer.msg("生效失败",{icon: 5})

                }
            });
        }



        /**
		 * 修改新增
         * @param edit
         * @param id
         */
        var addOrUpdateUser = function(edit,id){
            hasSave = false;
            var url = "";
            if(edit)
                url = path+"/users/editUser?id="+id;
            else
                url = path+"/users/addUser";
            var index = layui.layer.open({
                title : " ",
                type : 2,
                content : url,
                success : function(layero, index){
                    var body = layui.layer.getChildFrame('body', index);
                    setTimeout(function(){
                        layui.layer.tips('点此返回菜单列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                },
                end:function(){
                    if(hasSave) {
                        mytable.reload({
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where:{    //条件
                                "username":$("#name").val(),
								"enabled":$("#enabled").val()
                            }
                            , done: function (res, curr, count) {
                            }
                        })
                    }
				}
            })
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            })
        }

        //绑定
		$("#addUser").click(function(){
            addOrUpdateUser();
		})


	});
</script>
</body>
</html>